package com.huatai.bpmn.commom.util;

import com.alibaba.fastjson.JSONObject;
import com.huatai.bpmn.entity.dto.WeChatDeptDto;
import com.huatai.user.dto.WeChatPeopleDto;

import java.util.*;

/**
 * @author :yxy
 * @date : 2023/9/20
 */
public class NewWechatUtils {

	/**
	 * 获取企业token
	 * @return
	 */
	public static String getToken(String corpid,String corpsecret){
		String url="https://qyapi.weixin.qq.com/cgi-bin/gettoken";
		HashMap<String, String> map = new HashMap<>();
		map.put("corpid",corpid);
		map.put("corpsecret",corpsecret);
		String msg=null;
		try {
			msg = HttpsUtils.sendGet(url, null, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String token = JSONObject.parseObject(msg).getOrDefault("access_token", "").toString();
		return token;
	}

	/**
	 * 获取部门列表
	 * @return
	 */
	public static List<WeChatDeptDto> getDeptList(String token){
		HashMap<String, String> map = new HashMap<>();
		map.put("access_token", token);
		map.put("id", "");
		String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list";
		String deptList = null;
		try {
			deptList = HttpsUtils.sendGet(url, null, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<WeChatDeptDto> list = JSONObject.parseObject(deptList).getJSONArray("department").toJavaList(WeChatDeptDto.class);
		return list;
	}

	/**
	 * 获取部门人员详情
	 * @param departmentId
	 * @return
	 */
	public static List<WeChatPeopleDto> getDeptPeopleList(String token,String departmentId, String departmentName){
		HashMap<String, String> map = new HashMap<>();
		map.put("access_token", token);
		map.put("department_id", departmentId);
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list";
		String deptList = null;
		try {
			deptList = HttpsUtils.sendGet(url, null, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<WeChatPeopleDto> list = JSONObject.parseObject(deptList).getJSONArray("userlist").toJavaList(WeChatPeopleDto.class);
		list.forEach(x->x.setDepartName(departmentName));
		return list;
	}

	/**
	 * 获取人员信息
	 * @return
	 */
	public static Set<WeChatPeopleDto> getList(String token){
		LinkedHashSet<WeChatPeopleDto> list = new LinkedHashSet<>();
		List<WeChatDeptDto> deptList = getDeptList(token);
		deptList.forEach(x->{
			List<WeChatPeopleDto> deptPeopleList = getDeptPeopleList(token,x.getId(),x.getName());
			list.addAll(deptPeopleList);
		});
		Set<WeChatPeopleDto> userSet = new TreeSet<>(Comparator.comparing(WeChatPeopleDto::getUserid));
		userSet.addAll(list);
		return userSet;
	}
}
